# -*- coding: utf-8 -*-
import pycurl
import json
import urllib2
#import logging
#logger = logging.getLogger("django")

APPID = "wx6da18db64b616817"
APPSECRET = "4ffb0d0a0765ab8eacf54f1b834c61c9"
def wx_getReq(url):
	try:
		req = urllib2.Request(url)
		res_data = urllib2.urlopen(req)
		res = res_data.read()
	except Exception , e:
		#logger.debug(repr(e))
		res = ""
	return res
class WXUserInfo(object):
	def __init__(self,code):
		url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s"%APPID+"&secret=%s"%APPSECRET+"&code=%s"%code+"&grant_type=authorization_code"
		res = wx_getReq(url)
		data = json.loads(res)
		self.access_token = data["access_token"]
		self.openid = data["openid"]
	def getOpenId(self):
		return self.openid
	def getToken(self):
		return self.access_token
	def getUser(self):
		url ="https://api.weixin.qq.com/sns/userinfo?access_token=%s"%self.access_token+"&openid=%s"%self.openid+"&lang=zh_CN"
		res = wx_getReq(url)
		data = json.loads(res)
		print data
		#logger.debug(res)
		return data
	@staticmethod
	def getOauth2Url(url,once = 1,state = "state"):
		if once == 1:
			scope = "snsapi_userinfo"
		else:
			scope = "snsapi_base"
		Oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s"%APPID+"&redirect_uri=%s"%url+"&response_type=code&scope=%s"%scope+"&state=%s"%state+"#wechat_redirect"
		#logger.debug(Oauth2Url)
		return Oauth2Url
